import {
  Body,
  Controller,
  Get,
  Inject,
  Post,
  Query,
  Req,
  UploadedFile,
  UploadedFiles,
  UseInterceptors,
} from '@nestjs/common';
import { UploadFileService } from './uploadFile.service';
import { FileInterceptor, FilesInterceptor } from '@nestjs/platform-express';
import { storage } from 'src/utils/file';
import path from 'path';
import { Request } from 'express';
import * as fs from 'fs';
import * as oss from 'ali-oss';

@Controller('upload')
export class UploadFileController {
  @Inject(UploadFileService)
  private readonly uploadFileService: UploadFileService;

  private readonly ossConfig = {
    region: 'oss-cn-beijing',
    bucket: 'liam-liang-demo-2',
    accessKeyId: 'LTAI5t6pawmHFpR6g4XxfUjr',
    accessKeySecret: 'Psb4sD7Nir54DuEmsKY5UEQGYg23BX',
  };
  @Post('uploadImage')
  @UseInterceptors(
    FileInterceptor('file', {
      dest: 'uploads',
      storage: storage,
      limits: {
        fileSize: 1024 * 1024 * 5, // 5MB
      },
      fileFilter: (req, file, cb) => {
        const extname = path.extname(file.originalname);
        if (['.png', '.jpg', '.gif', '.jpeg'].includes(extname)) {
          cb(null, true);
        } else {
          cb(new Error('只能上传图片'), false);
        }
      },
    }),
  )
  uploadCover(
    @UploadedFile() file: Express.Multer.File,
    @Req() request: Request,
  ) {
    const serverAddress = `${request.protocol}://${request.get('host')}`;
    const fileUrl = `${serverAddress}/${file.path}`;
    return {
      code: 0,
      message: '上传成功',
      data: {
        url: fileUrl,
      },
    };
  }

  @Post('uploadFiles')
  @UseInterceptors(
    FilesInterceptor('files', 20, {
      dest: 'uploads',
    }),
  )
  uploadFiles(
    @UploadedFiles() files: Express.Multer.File[],
    @Body() body: { name: string },
  ) {
    const fileName = body.name.match(/(.+)\-\d+$/)[1];
    const chunkDir = 'uploads/chunks_' + encodeURIComponent(fileName);
    if (!fs.existsSync(chunkDir)) {
      fs.mkdirSync(chunkDir);
    }
    console.log(files);
    fs.cpSync(files[0].path, chunkDir + '/' + body.name);
    fs.rmSync(files[0].path);
    return {
      code: 0,
      message: '上传成功',
      data: {
        // url: fileUrl,
      },
    };
  }

  // 分片上传文件合并
  @Get('merge')
  merge(@Query('name') name: string) {
    const chunkDir = 'uploads/chunks_' + encodeURIComponent(name);

    const files = fs.readdirSync(chunkDir);

    let startPos = 0;
    let count = 0;

    files
      .sort((a, b) => this.getNumberFromEnd(a) - this.getNumberFromEnd(b))
      .map((file) => {
        const filePath = chunkDir + '/' + file;
        const stream = fs.createReadStream(filePath);
        stream
          .pipe(fs.createWriteStream('uploads/' + name, { start: startPos }))
          .on('finish', () => {
            count++;

            if (count === files.length) {
              fs.rm(
                chunkDir,
                {
                  recursive: true,
                },
                () => {},
              );
            }
          });
        startPos += fs.statSync(filePath).size;
      });
  }
  getNumberFromEnd(str) {
    const regex = /-(\d+)$/;
    const match = str.match(regex);
    return match ? parseInt(match[1]) : null;
  }

  @Get('ossTemp')
  async ossTemp() {
    const client = new oss(this.ossConfig);
    const date = new Date();
    date.setDate(date.getDate() + 1);
    const res = client.calculatePostSignature({
      expiration: date.toISOString(),
      conditions: [
        ['content-length-range', 0, 1048576000], //设置上传文件的大小限制。
      ],
    });
    console.log(res);

    const location = await client.getBucketLocation();

    const host = `http://${this.ossConfig.bucket}.${location.location}.aliyuncs.com`;

    console.log(host);
    return {
      code: 0,
      message: '获取成功',
      data: {
        ...res,
        host,
      },
    };
  }
}
